package main

import (
	"encoding/json"
	"fmt"
	"net"
	"sync"
	"sync/atomic"
)

// 客户端连接到服务端并发起请求
func CallServer(address, method string, args []any) (string, error) {
	// 连接到服务端
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return "", err
	}
	defer conn.Close()

	method = "Add"
	args = []any{1, 2}

	data, _ := json.Marshal(struct {
		Method string `json:"method"`
		Args   []any  `json:"args"`
	}{
		Method: method,
		Args:   args,
	})
	fmt.Println(string(data))
	// 发送请求
	fmt.Fprintf(conn, "%s\n", data)

	// 接收响应
	var reply string
	fmt.Fscanf(conn, "%s", &reply)
	return reply, nil
}

func main() {
	// 调用服务端的方法
	// reply, err := CallServer(":1234", "Add", []interface{}{2, 3})
	// if err != nil {
	// 	fmt.Println("Error calling server:", err)
	// 	return
	// }

	// // 打印服务端返回的结果
	// fmt.Println("Server response:", reply)

	var counter int32

	var wg sync.WaitGroup

	for i := 0; i < 1000; i++ {
		wg.Add(1)

		go func() {
			defer wg.Done()

			atomic.AddInt32(&counter, 1)

		}()
	}

	wg.Wait()

	fmt.Println(counter)
}
